# -*- coding: utf8  -*-

from __future__ import print_function
import gevent
import gevent.monkey
gevent.monkey.patch_all()

import time
import random
import multiprocessing

from phoenix_mns.mns_log.log import logger
from phoenix_mns.consumer.consumer import MultiProcessService, GeventService

MaxThread = multiprocessing.cpu_count()
MaxThread = 4


class DemoService(MultiProcessService):

    def init_consume_list(self):
        """
        :return:
        """
        self.consume_list = [
            'print_msg'
        ]

    def random_sleep(self):
        s = random.randint(1, 3)
        time.sleep(s)
        self.statistic_dict['random'] = s
        logger.debug("sleep random")
        return True

    def print_msg(self):
        print(self.consume_msg)
        self.statistic_dict['p_succ'] = 1
        return True


class DemoGeventService(GeventService):

    def init_consume_list(self):
        """
        :return:
        """
        self.consume_list = [
            'start_func',
            'random_sleep',
            'done_func',
        ]

    def random_sleep(self, payload, dcount):
        s = random.randint(3, 7)
        print('random sleep', s, payload, dcount)
        gevent.sleep(s)
        return True

    def start_func(self, payload, dcount):
        print('start', payload, dcount)
        return True

    def done_func(self, payload, dcount):
        print('done', payload, dcount)
        return True


def mns_consumer():
    """
    this is demo consumer
    @return:
    """
    job_list = []
    for i in range(MaxThread):
        thread_jobworker = DemoService("./conf/service_sample.cfg", "./conf/sample.cfg")
        thread_jobworker.daemon = False
        thread_jobworker.start()
        job_list.append(thread_jobworker)

    for job in job_list:
        job.join()


def gevent_mns_consumer():
    jobs = []
    for i in range(3):
        job = DemoGeventService("conf/service_sample.cfg", "conf/sample.cfg")
        job.start()
        jobs.append(job)

    for job in jobs:
        job.join()


if __name__ == "__main__":
    # 3850条记录
    mns_consumer()  # 90s
    # gevent_mns_consumer() # 28s
